package com.wangyadong.hobby.schedule.jobtask.javasync.Reference;


import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/11/1611:07
 **/
public class LRUCache<K, V> {

    private final LinkedList<K> keyList = new LinkedList();

    private final Map<K, V> cache = new HashMap<>();


    //cache 最大容量
    private final int capacity;

    private final CacheLoader<K, V> cacheLoader;

    public LRUCache(int capacity, CacheLoader cacheLoader) {
        this.cacheLoader = cacheLoader;
        this.capacity = capacity;
    }

    public void put(K k, V v) {
        if (keyList.size() > capacity) {
            K o = keyList.removeFirst();
            cache.remove(o);
        }
        if (keyList.contains(k)) {
            keyList.remove(k);
        }
        keyList.addLast(k);
        cache.put(k, v);
    }

    public  V get(K k)   {
        V value;
        boolean removeFlag = keyList.remove(k);
        if (!removeFlag) {
            value = cacheLoader.load(k);
            this.put(k, value);
        } else {
            value = cache.get(k);
            keyList.addLast(k);
        }
        return value;
    }

    @Override
    public String toString() {
        return this.keyList.toString();
    }
}
